package so.sao.shop.supplier.util;

import so.sao.shop.supplier.domain.Purchase;
import so.sao.shop.supplier.domain.PurchaseItem;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 优惠券规则工具类
 *
 * @author gxy on 2017/11/1.
 */
public class CouponRulesUtil {

    /**
     * 计算优惠金额
     *
     * @param listPurchase 订单列表
     * @param listItem 订单明细列表
     * @param couponValue  优惠券金额
     * @return 优惠后的商品价格表
     */
    public static Map<String,Object> couponRule(List<Purchase> listPurchase, List<PurchaseItem> listItem, BigDecimal couponValue) {
        //返回参数
        Map<String,Object> output = new HashMap<>();
        couponValue = couponValue.setScale(2,BigDecimal.ROUND_HALF_UP);
        //每个orderId优惠金额的map
        //优惠前总金额
        BigDecimal beforeTotal = BigDecimal.valueOf(0);
        for (PurchaseItem purchaseItem : listItem) {
            beforeTotal = beforeTotal.add(purchaseItem.getGoodsTatolPrice());
        }
        //优惠后总金额
        BigDecimal afterTotal = new BigDecimal(0);
        //计算每个SKU优惠金额
        for (PurchaseItem purchaseItem : listItem){
            BigDecimal goodsTatolPrice = purchaseItem.getGoodsTatolPrice();
            //计算折扣优惠
            BigDecimal discount = goodsTatolPrice.multiply(couponValue).divide(beforeTotal,2,RoundingMode.HALF_UP);
            purchaseItem.setGoodsDiscount(discount);
            afterTotal = afterTotal.add(goodsTatolPrice.subtract(discount).setScale(2,BigDecimal.ROUND_HALF_UP));
        }
        //除不尽 误差值
        BigDecimal error = (afterTotal.add(couponValue)).subtract(beforeTotal);
        if (error.compareTo(BigDecimal.ZERO) != 0) {
            listItem.get(listItem.size() - 1).setGoodsDiscount(listItem.get(listItem.size() - 1).getGoodsDiscount().add(error));
        }

        //计算每个orderId优惠金额
        for (Purchase purchase : listPurchase) {
            //SKU优惠总计,以orderId为维度
            BigDecimal goodsTotalDiscount = new BigDecimal(0);
            for (PurchaseItem purchaseItem:listItem) {
                if (purchaseItem.getOrderId().equals(purchase.getOrderId())){
                    goodsTotalDiscount = goodsTotalDiscount.add(purchaseItem.getGoodsDiscount());
                }
            }
            //计算合计金额
            purchase.setOrderTotalPrice(purchase.getOrderTotalPrice().subtract(goodsTotalDiscount));
            purchase.setDiscount(goodsTotalDiscount);
        }
        output.put("listPurchase",listPurchase);
        output.put("listItem",listItem);
        return output;
    }
}
